import 'dart:convert';
import 'package:get/get.dart';
import 'package:repair_pda/model/response_result.dart';
import 'package:repair_pda/model/login_model.dart';

class ApiService extends GetConnect {
  // 基础URL配置
  @override
  void onInit() {
    //TODO: 修改后台域名
    httpClient.baseUrl = 'http://192.168.0.68/showabe';
    httpClient.defaultContentType = 'application/json';
    httpClient.timeout = Duration(seconds: 30);
    super.onInit();
  }

  //#region 测试网络连通
  Future<ResponseResult<String>> test(List<int> ids) async {
    httpClient.baseUrl = 'http://192.168.0.68/showabe';
    httpClient.defaultContentType = 'application/json';
    httpClient.timeout = Duration(seconds: 30);

    try {
      final response = await post(
        '/dev/now','' // 登录接口路径
      );

      if (response.statusCode == 200) {
        // 成功响应，反序列化数据
        return ResponseResult<String>.fromJson(response.body);
      } else {
        // 错误响应
        return ResponseResult<String>(
          success: false,
          code: response.statusCode,
          msg: response.statusText,
        );
      }
    } catch (e) {
      // 异常处理
      return ResponseResult<String>(
        success: false,
        code: -1,
        msg: e.toString(),
      );
    }
  }
  //#endregion

  //#region 测试post参数
  Future<ResponseResult<String>> testPostParam() async {
    try {
      final response = await post(
        '/dev/getPurchaseEmailContent',
        jsonEncode([3688])
      );

      if (response.statusCode == 200) {
        // 成功响应，反序列化数据
        return ResponseResult<String>.fromJson(response.body);
      } else {
        // 错误响应
        return ResponseResult<String>(
          success: false,
          code: response.statusCode,
          msg: response.statusText,
        );
      }
    } catch (e) {
      // 异常处理
      return ResponseResult<String>(
        success: false,
        code: -1,
        msg: e.toString(),
      );
    }
  }
  //#endregion

  //#region 登录方法
  Future<ResponseResult<LoginModel>> login(LoginModel loginModel) async {
    try {
      final response = await post(
        '/login', // 登录接口路径
        loginModel.toJson(),
      );

      if (response.statusCode == 200) {
        // 成功响应，反序列化数据
        return ResponseResult<LoginModel>.fromJson(response.body);
      } else {
        // 错误响应
        return ResponseResult<LoginModel>(
          success: false,
          code: response.statusCode,
          msg: response.statusText,
        );
      }
    } catch (e) {
      // 异常处理
      return ResponseResult<LoginModel>(
        success: false,
        code: -1,
        msg: e.toString(),
      );
    }
  }
  //#endregion
}